package com.efounder.message.db;

import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.os.Environment;
import android.util.Log;

import com.efounder.constant.EnvironmentVariable;
import com.efounder.frame.utils.EFConstants;

import java.io.File;

public class MessageDBHelper extends SQLiteOpenHelper {
    private static final String TAG = "MessageDBHelper";
    //数据库版本号 2018/12/11修改 yqs
    private static final int DATABASE_VERSION = 20;

    public MessageDBHelper(Context context) {
        super(context, getMyDatabaseName(context), (CursorFactory) null, DATABASE_VERSION);
//        Log.i("db-----", "MessageDBHelper-----开始创建");

    }

    private static String getMyDatabaseName(Context context) {
        //sd卡是否可用
        boolean isSdCardEnable = Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState());


        String dbPath = null;
        String userID = EnvironmentVariable.getUserID();
        if (userID == null || userID.equals("")) {
//            throw new RuntimeException("MessageDBHelper exception:env-userID is null");
            Log.e(TAG, "MessageDBHelper exception:env-userID is null");
            userID = "-1";
        }
        if (isSdCardEnable) {
            dbPath = EFConstants.APP_ROOT + "/" + userID + "/";
        } else {
            dbPath = context.getFilesDir().getPath() + "/database/" + userID + "/";
        }

        File dbp = new File(dbPath);
        if (!dbp.exists()) {
            dbp.mkdirs();
        }

        String databasename = dbPath + "OSPMobileChat.db";
//        Log.i("db-----", "MessageDBHelper-----数据库名称：" + databasename);
        return databasename;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        try {
            db.execSQL("CREATE TABLE ChatList(loginUserId INTEGER,userId INTEGER,messageId INTEGER,unReadCount INTEGER,chatType INTEGER,msgID TEXT,enable INTEGER DEFAULT 1,constraint pk_cl primary key (loginUserId,userId,chatType) );");
            db.execSQL("CREATE TABLE Message( messageId Integer,msgID TEXT, fromUserId INTEGER,toUserId INTEGER,time TIMESTAMP,serverTime TIMESTAMP,localTime TIMESTAMP,toUserType INTEGER,messageChildType INTEGER,body BLOB,bodyString text,isRecall INTEGER default 0,state INTEGER ,enable INTEGER DEFAULT 1,readState INTEGER,version INTEGER,pMsgId TEXT,pUserId INTEGER,extra TEXT DEFAULT \'\', constraint pk_t2 primary key (fromUserId,toUserId,time,msgID,toUserType));");
            db.execSQL("CREATE TABLE Friends (loginUserId INTEGER, userId INTEGER, isTop INTEGER, isBother Integer, remark TEXT, isImportent INTEGER,remark_py_initial text  default '', remark_py_quanpin text  default '',enable INTEGER DEFAULT 1, CONSTRAINT pk_f PRIMARY KEY (loginUserId, userId));");
            db.execSQL("CREATE TABLE Groups (groupId INTEGER PRIMARY KEY, createUserId INTEGER, groupName TEXT, createTime TIMESTAMP,avatar TEXT,no_speak INTEGER DEFAULT 0,group_type INTEGER DEFAULT 0,english_name text default '',recommend text DEFAULT '',py_initial text  default '',py_quanpin text  default '', enable INTEGER DEFAULT 1);");
            db.execSQL("CREATE TABLE GroupUsers(groupId INTEGER, userId INTEGER,ownRemark TEXT DEFAULT \'\',otherRemark TEXT DEFAULT \'\',groupUserType INTEGER DEFAULT 0,g_user_no_speak INTEGER  default 0,enable INTEGER DEFAULT 1,constraint pk_gu primary key (groupId,userId));");
            db.execSQL("CREATE TABLE MyGroup(groupId INTEGER ,loginUserId INTEGER, isTop INTEGER,isBother INTEGER,enable INTEGER DEFAULT 1, constraint pk_mg primary key (loginUserId,groupId));");
            db.execSQL("CREATE TABLE NewFriend ( loginUserId INTEGER,userId INTEGER,  time TIMESTAMP,  state INTEGER,isRead INTEGER,enable INTEGER DEFAULT 1,leave_message text  default '', constraint pk_n primary key (loginUserId,userId));");
            db.execSQL("CREATE TABLE User (userId INTEGER PRIMARY KEY, name TEXT, nickName TEXT, sex TEXT, phone TEXT, mobilephone TEXT, avatar TEXT, email TEXT, sigNature TEXT, deptId INTEGER,  type INTEGER, enable INTEGER DEFAULT 1," +
                    " walletAddress TEXT,publicKey TEXT,RSAPublicKey TEXT,wechatQrUrl TEXT,zhifubaoQrUrl TEXT,nickname_py_initial text  default '',nickname_py_quanpin text  default '',planet text default '',stranger_chat INTEGER  default 1);");
            db.execSQL("CREATE TABLE ReadCount( id TEXT,messageID TEXT, unReadCount INTEGER,atMessageID TEXT,enable INTEGER DEFAULT 1, primary key (id));");
            db.execSQL("CREATE TABLE GroupNotice ( groupId INTEGER,userId INTEGER, time TIMESTAMP, state INTEGER,isRead INTEGER,enable INTEGER DEFAULT 1,leave_message text  default '', constraint pk_n primary key (groupId,userId));");
        } catch (SQLException var3) {
            var3.printStackTrace();
        }

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        try {
            if (oldVersion <= 6) {
                db.execSQL("alter table message add serverTime TIMESTAMP;");
                db.execSQL("alter table message add localTime TIMESTAMP;");
            }

            if (oldVersion <= 7) {
                db.execSQL("alter table groupusers add groupUserType INTEGER DEFAULT 0;");
            }
            if (oldVersion <= 8) {
                db.execSQL("CREATE TABLE GroupNotice ( groupId INTEGER,userId INTEGER, time TIMESTAMP, state INTEGER,isRead INTEGER,enable INTEGER DEFAULT 1, constraint pk_n primary key (groupId,userId));");
            }
            if (oldVersion <= 9) {
                db.execSQL("alter table Message add extra TEXT DEFAULT \'\';");
            }
            if (oldVersion <= 10) {
                db.execSQL("alter table User add walletAddress TEXT;");
                db.execSQL("alter table User add publicKey TEXT;");

            }
            if (oldVersion <= 11) {
                db.execSQL("alter table User add RSAPublicKey TEXT;");
            }
            if (oldVersion <= 12) {
                db.execSQL("alter table User add wechatQrUrl TEXT ");
                db.execSQL("alter table User add zhifubaoQrUrl TEXT ");

            }
            if (oldVersion <= 13) {
                db.execSQL("alter table Message add bodyString TEXT  default '';");
            }
            if (oldVersion <= 14) {
                db.execSQL("alter table Message add isRecall INTEGER  default 0;");
                db.execSQL("alter table User add stranger_chat INTEGER  default 1;");
                db.execSQL("alter table Groups add no_speak INTEGER  default 0;");
                db.execSQL("alter table Groups add group_type INTEGER DEFAULT 0;");
                db.execSQL("alter table GroupUsers add g_user_no_speak INTEGER  default 0;");
            }
            if (oldVersion <= 15) {
                //groups增加英文名、群介绍的字段
                db.execSQL("alter table Groups add english_name text  default '';");
                db.execSQL("alter table Groups add recommend text DEFAULT '';");

            }
            if (oldVersion <= 16) {
                //新的好友 群通知 增加新字段
                db.execSQL("alter table NewFriend add leave_message text  default '';");
                db.execSQL("alter table GroupNotice add leave_message text default '';");

            }
            if (oldVersion <= 17) {
                //新增atmessageId 字段
                db.execSQL("alter table ReadCount add atMessageID text  default '';");
            }
            if (oldVersion <= 18) {
                //新增昵称 群名称全拼 简拼字段
                db.execSQL("alter table Groups add py_initial text  default '';");
                db.execSQL("alter table Groups add py_quanpin text  default '';");
                db.execSQL("alter table User add nickname_py_initial text  default '';");
                db.execSQL("alter table User add nickname_py_quanpin text  default '';");
                db.execSQL("alter table Friends add remark_py_initial text  default '';");
                db.execSQL("alter table Friends add remark_py_quanpin text  default '';");
            }
            if (oldVersion <= 19) {
                //新增用户星球字段
                db.execSQL("alter table User add planet text default '';");
            }
        } catch (SQLException var5) {
            var5.printStackTrace();
        }

    }
}
